﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:getx_scaffold/common/utils/toast_util.dart';
import 'heart_rate_logic.dart';
import 'heart_rate_detail_view.dart';
import '../../../core/models/heart_rate_model.dart' as api_models;

/// 心率记录页面
class HeartRateListView extends GetView<HeartRateLogic> {
  const HeartRateListView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: Text(
          '心率记录',
          style: TextStyle(
            fontSize: 20.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Get.back(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.calendar_today, color: Colors.white),
            onPressed: () => _showDatePicker(context),
          ),
          IconButton(
            icon: const Icon(Icons.refresh, color: Colors.white),
            onPressed: () => controller.getHeartRateList(),
          ),
        ],
      ),
      body: SafeArea(
        child: Obx(() {
          if (controller.isLoadingApiData.value) {
            return const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFFD700)),
              ),
            );
          }

          if (controller.heartRateList.isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.favorite_border,
                    size: 64.sp,
                    color: Colors.grey[600],
                  ),
                  SizedBox(height: 16.h),
                  Text(
                    '暂无心率记录',
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.grey[400],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    '点击刷新按钮获取数据',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[500],
                    ),
                  ),
                  SizedBox(height: 24.h),
                  ElevatedButton(
                    onPressed: () => controller.getHeartRateList(),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFFFFD700),
                      foregroundColor: Colors.black,
                      padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
                    ),
                    child: Text(
                      '刷新数据',
                      style: TextStyle(fontSize: 14.sp),
                    ),
                  ),
                ],
              ),
            );
          }

          // 按日期分组心率记录
          final groupedRecords = _groupRecordsByDate(controller.heartRateList);
          
          return ListView.builder(
            padding: EdgeInsets.zero,
            itemCount: groupedRecords.length,
            itemBuilder: (context, index) {
              final dateGroup = groupedRecords[index];
              return _buildDateGroup(dateGroup);
            },
          );
        }),
      ),
    );
  }

  /// 按日期分组记录
  List<MapEntry<String, List<api_models.HeartRateRecord>>> _groupRecordsByDate(
    List<api_models.HeartRateRecord> records
  ) {
    final Map<String, List<api_models.HeartRateRecord>> grouped = {};
    
    for (final record in records) {
      if (record.endTime != null) {
        try {
          final dateTime = DateTime.parse(record.endTime!);
          final dateKey = '${dateTime.year}年${dateTime.month.toString().padLeft(2, '0')}月${dateTime.day.toString().padLeft(2, '0')}日,${_getWeekday(dateTime.weekday)}';
          
          if (!grouped.containsKey(dateKey)) {
            grouped[dateKey] = [];
          }
          grouped[dateKey]!.add(record);
        } catch (e) {
          // 忽略解析错误的记录
        }
      }
    }
    
    // 按日期排序（最新的在前）
    final sortedEntries = grouped.entries.toList()
      ..sort((a, b) {
        try {
          final dateA = _parseDateFromKey(a.key);
          final dateB = _parseDateFromKey(b.key);
          return dateB.compareTo(dateA);
        } catch (e) {
          return 0;
        }
      });
    
    return sortedEntries;
  }

  /// 从日期键解析日期
  DateTime _parseDateFromKey(String dateKey) {
    final parts = dateKey.split(',')[0].split('年');
    final year = int.parse(parts[0]);
    final monthDay = parts[1].split('月');
    final month = int.parse(monthDay[0]);
    final day = int.parse(monthDay[1].replaceAll('日', ''));
    return DateTime(year, month, day);
  }

  /// 获取星期几的中文表示
  String _getWeekday(int weekday) {
    switch (weekday) {
      case 1:
        return '周一';
      case 2:
        return '周二';
      case 3:
        return '周三';
      case 4:
        return '周四';
      case 5:
        return '周五';
      case 6:
        return '周六';
      case 7:
        return '周日';
      default:
        return '';
    }
  }

  /// 构建日期组
  Widget _buildDateGroup(MapEntry<String, List<api_models.HeartRateRecord>> dateGroup) {
    final dateKey = dateGroup.key;
    final records = dateGroup.value;
    
    // 按时间排序（最新的在前）
    records.sort((a, b) {
      if (a.endTime == null || b.endTime == null) return 0;
      try {
        final timeA = DateTime.parse(a.endTime!);
        final timeB = DateTime.parse(b.endTime!);
        return timeB.compareTo(timeA);
      } catch (e) {
        return 0;
      }
    });

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 日期标题
        Padding(
          padding: EdgeInsets.only(left: 20.w, top: 20.h, bottom: 12.h),
          child: Text(
            dateKey,
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey[400],
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
        
        // 心率记录列表
        ...records.map((record) => _buildHeartRateItem(record)).toList(),
        
        // 底部分隔线
        if (dateGroup != _groupRecordsByDate(controller.heartRateList).last)
          Divider(
            color: Colors.grey[800],
            height: 1.h,
            thickness: 1.w,
          ),
      ],
    );
  }

  /// 构建心率记录项
  Widget _buildHeartRateItem(api_models.HeartRateRecord record) {
    final heartRate = record.heartRate ?? 0;
    final endTime = record.endTime;
    
    // 解析时间
    String timeDisplay = '';
    if (endTime != null) {
      try {
        final measurementTime = DateTime.parse(endTime);
        timeDisplay = '${measurementTime.hour.toString().padLeft(2, '0')}:${measurementTime.minute.toString().padLeft(2, '0')}';
      } catch (e) {
        timeDisplay = '时间解析错误';
      }
    }

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => _navigateToHeartRateDetail(record),
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 16.h),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Colors.grey[800]!,
                  width: 0.5.w,
                ),
              ),
            ),
            child: Row(
              children: [
                // 心率值
                Text(
                  '$heartRate',
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w600,
                    color: const Color(0xFFFFD700),
                  ),
                ),
                SizedBox(width: 8.w),
                Text(
                  'BPM',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[400],
                  ),
                ),
                
                const Spacer(),
                
                // 时间
                Text(
                  timeDisplay,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.white,
                  ),
                ),
                
                SizedBox(width: 8.w),
                
                // 箭头
                Icon(
                  Icons.arrow_forward_ios,
                  size: 12.sp,
                  color: Colors.grey[400],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 显示日期选择器
  void _showDatePicker(BuildContext context) {
    showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime.now().subtract(const Duration(days: 365)),
      lastDate: DateTime.now(),
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: ColorScheme.dark(
              primary: const Color(0xFFFFD700),
              onPrimary: Colors.black,
              surface: Colors.grey[900]!,
              onSurface: Colors.white,
            ),
          ),
          child: child!,
        );
      },
    ).then((selectedDate) {
      if (selectedDate != null) {
        // 这里可以添加按日期筛选的逻辑
        // TODO: 实现按日期筛选功能
        Toast.show(
          '日期筛选功能开发中',
         
        );
      }
    });
  }

  /// 跳转到心率详情页面
  void _navigateToHeartRateDetail(api_models.HeartRateRecord record) async {
    if (record.dailyValue == null) {
      Toast.show(
        '无法获取该记录的详细信息',
        
      );
      return;
    }

    try {
      Get.dialog(
        const Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFFD700)),
          ),
        ),
        barrierDismissible: false,
      );

      final detailList = await controller.getHeartRateDetail(record.dailyValue!);
      
      Get.back(); // 关闭加载对话框

      if (detailList.isNotEmpty) {
        Get.to(() => HeartRateDetailView(
          dailyValue: record.dailyValue!,
          heartRateList: detailList,
        ));
      } else {
        Toast.show(
          '该日期暂无详细记录',
         
        );
      }
    } catch (e) {
      Get.back(); // 关闭加载对话框
      Toast.show(
        '获取详情失败: $e',
      );
    }
  }
}


